package com.jm.day24.c_demo1;

import com.jm.day24.utils.JdbcUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;

/**
 * 这种方式不推荐使用。因为代码耦合性太强，业务处理代码和数据库操作的代码依赖性过强，不利于代码的维护和功能扩展
 *
 * @author liuyp
 */
public class TransferDemo1 {

    /**银行转账方法
     * @param out  转账人
     * @param in 收款人
     * @param money 转账金额
     * @return
     */
    public boolean transfer(String out, String in, Double money){
        boolean isSuccess = true;
        //创建QueryRunner对象，用来执行sql语句，不需要传连接池进去
        QueryRunner runner = new QueryRunner();
        Connection conn = null;
        try{
            //获取连接，开启事务
            conn = JdbcUtils.getConnection();
            conn.setAutoCommit(false);

            //执行转账人扣钱的操作
            runner.update(conn, "update account set money = money - ? where username = ?", money, out);

            //执行收款人加钱的操作
            runner.update(conn, "update account set money = money + ? where username = ?", money, in);

            //如果没有异常，提交事务
            DbUtils.commitAndCloseQuietly(conn);
        }catch(Exception e){
            //有异常，回滚事务
            DbUtils.rollbackAndCloseQuietly(conn);
            isSuccess = false;
        }


        return isSuccess;
    }

    public static void main(String[] args) {
        //定义参数
        String out = "zhangsan";
        String in = "lisi";
        Double money = 500d;

        TransferDemo1 transfer = new TransferDemo1();
        boolean isSuccess = transfer.transfer(out, in, money);
        if(isSuccess){
            System.out.println("转账成功");
        }else{
            System.out.println("转账失败");
        }
    }

}
